package cn.mugutu.sort;

import org.junit.Test;

/**
 * Created by gan on 2018/3/21 13:56.
 */
public class BubbleSort {

    @Test
    public void bubbleSort() {
        int[] arr = {2, 3, 445, 545, 11}; //原始数组
        int temp;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {    //前一个比后一个大就交换
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

    }

    //或者

    @Test
    public void bubbleSort2() {
        int[] arr = {2, 3, 445, 545, 11}; //原始数组
        int temp;
        for (int i = arr.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        Character c = 'A';
    }


    //选择排序法
    @Test
    public void selectionSort() {
        int[] arr = {112, 23, 44, 4, 312};
        int temp;   //用于交换的临时变量
        int min;    //用来记录每次最小值的数组下标
        for (int i = 0; i < arr.length-1; i++) {

            min = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
                }

                System.out.println("===========i===>" + i + "========j===>" + j);
            }

            //判断是否找到有比这一轮排序的第一个数还小的
            if (min != i) {
                temp = arr[min];
                arr[min] = arr[i];
                arr[i] = temp;
            }
        }

        //打印
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
